var express = require('express'),
  router = express.Router();
  mongoose = require('mongoose'),
  Post = mongoose.model('Post'),
  Category = mongoose.model('Category');


module.exports = function (app) {
  app.use('/posts', router);
};

// 首页
router.get('/', function (req, res, next) {
  Post.find().populate('author').populate('category').exec(function (err, posts) {
    if (err) return next(err);
    res.render('index', {
      title: 'Generator-Express MVC',
      posts: posts
    });
  });
});

// 文章详情
router.get('/:id', function (req, res, next) {
  if (!req.params.id) {
    return next(new Error('no post in provided'));
  }
  // var conditions = {};
  // try {
  //   conditions._id = mongoose.Types.ObjectId(req.params.id);
  // } catch (err) {
  //   conditions.slug = req.params.id;
  // }
  Post.findOne({_id: req.params.id})
      .populate('category')
      .populate('author')
      .exec(function (err, post) {
        if (err) return next(err);
        res.render('post', {
          title: '文章详情',
          posts: post
        });
      });
});

// 点赞
router.get('/favourates/:id', function (req, res, next) {
  if (!req.params.id) {
    return next(new Error('no post in provided'));
  }
  Post.findOne({_id: req.params.id})
      .populate('category')
      .populate('author')
      .exec(function (err, post) {
        if (err) return next(err);
        post.meta.favourates =  post.meta.favourates ? post.meta.favourates + 1 : 1;
        post.markModified('meta'); // 手动标记已修改
        post.save(function (err) {
          res.redirect('/posts/' + post._id);
          // res.render('post', {
          //   title: '文章详情',
          //   post: post
          // });
        });
      });
});

// 评论
router.post('/comment/:id', function (req, res, next) {
    if (!req.body.email) return next(new Error('no email provided for commenter'));
    if (!req.body.content) return next(new Error('no email provided for commenter'));
    Post.findOne({_id: req.params.id}).exec(function (err, post) {
      if (err) return next(err);
      var comment = {
        email: req.body.email,
        content: req.body.content,
        created: new Date()
      };
      post.comments.unshift(comment);
      post.markModified('comments');
      post.save(function (err) {
        req.flash("info", "评论添加成功！");
        res.redirect('/posts/' + post._id);
      });
    });
});

// 分类列表
router.get('/category/:name', function (req, res, next) {
  Category.findOne({name: req.params.name}).exec(function (err, category) {
    if (err) return next(err);
    Post.find({category: category, published: true})
        .sort('created')
        .populate('category')
        .populate('author')
        .exec(function (err, post) {
          if (err) return next(err);
          res.render('category', {
            title: '分类列表',
            category: category,
            posts: post
          });
        });
  });
});
